<template>
    <!-- 建议将其修改为页面 增加在线编辑题目描述 -->
    <!-- 这里应该是题目管理，上传与修改题目都在这里 -->
    <n-tabs
        type="line"
        justify-content="space-evenly"
        size="large"
        @before-leave="handleBeforeLeave"
    >
        <n-tab-pane name="uploadQuestion" tab="上传题目">
            <n-space vertical style="margin-left: 5%;">
                <n-h1>题目名</n-h1>
                <n-space align="center">
                    <n-input
                        placeholder="请输入题目名称"
                        v-model:value="uploadQuestion.questionName"
                        style="width: 500px;"
                    ></n-input>
                    <n-button
                        type="primary"
                        @click="check"
                        :disabled="uploadQuestion.questionName.length == 0"
                    >查询重复</n-button>
                </n-space>
                <n-h1 style="margin-top: 2%;">题目描述</n-h1>
                <n-h3 v-if="!uploadQuestion.editOnline">请上传markdown文件</n-h3>
                <n-switch v-model:value="uploadQuestion.editOnline" :round="false">
                    <template #checked>在线编辑</template>
                    <template #unchecked>上传文件</template>
                </n-switch>
                <div style="width: 90%;" v-if="uploadQuestion.editOnline">
                    <v-md-editor height="500px" v-model="uploadQuestion.description"></v-md-editor>
                </div>
                <n-space vertical>
                    <n-upload
                        @change="descriptionChange"
                        ref="description"
                        name="description_file"
                        action="http://localhost:8000/sql/questions/create"
                        :data="{
                            difficulty: uploadQuestion.difficulty,
                            name: uploadQuestion.questionName,
                            categories_id: String(uploadQuestion.tags)
                        }"
                        @finish="setNo"
                        @before-upload="beforeUpload"
                        :headers="uploadHeaders"
                        :default-upload="false"
                        style="width: 90%;"
                        v-if="!uploadQuestion.editOnline"
                    >
                        <n-button>选择题目描述</n-button>
                    </n-upload>
                    <n-divider style="width: 90%;"></n-divider>
                    <n-h1>标签</n-h1>
                    <n-select
                        style="width: 300px;"
                        placeholder="请选择标签"
                        :options="tags"
                        v-model:value="uploadQuestion.tags"
                    ></n-select>
                    <n-divider style="width: 90%;"></n-divider>
                    <n-h1>难度</n-h1>
                    <n-select
                        style="width: 300px;"
                        placeholder="请选择难度"
                        :options="difficulties"
                        v-model:value="uploadQuestion.difficulty"
                    ></n-select>
                    <n-divider style="width: 90%;"></n-divider>
                    <n-h1>输入和输出文件</n-h1>
                    <n-h3>请注意：请以判题组号.文件名作为文件，并成组，（例如1.in和1.out）</n-h3>
                    <n-space vertical>
                        <div>
                            <n-upload
                                @change="dataChange"
                                @before-upload="beforeUploadData"
                                multiple
                                name="data"
                                action="http://localhost:8000/sql/questions/upload_test_data"
                                :headers="uploadHeaders"
                                :data="{
                                    question_id: String(uploadQuestion.questionNo),
                                }"
                                ref="data"
                                :default-upload="false"
                                style="width: 90%;"
                            >
                                <n-button>选择输入和输出文件</n-button>
                            </n-upload>
                        </div>
                        <n-button
                            size="large"
                            type="primary"
                            @click="handleClick"
                            :disabled="!uploadQuestion.diff || (!uploadQuestion.files.description.exist == (uploadQuestion.description.length == 0)) || uploadQuestion.uploadData"
                        >创建题目</n-button>
                    </n-space>
                </n-space>
                <n-divider style="width: 90%;"></n-divider>
                <n-space></n-space>
            </n-space>
        </n-tab-pane>
        <n-tab-pane name="deleteQuestion" tab="删除题目">
            <n-space vertical style="margin-left: 5%;">
                <n-h1>删除题目</n-h1>
                <n-space align="center">
                    <n-input
                        placeholder="请输入题目名称"
                        v-model:value="deleteQuestion.questionName"
                        style="width: 500px;"
                    ></n-input>
                    <n-button type="primary" @click="checkNoExists">查询是否存在</n-button>
                </n-space>
                <n-button size="large" type="primary" @click="deleteQuestions">删除</n-button>
            </n-space>
        </n-tab-pane>
    </n-tabs>
</template>

<script lang='ts'>
import { defineComponent, ref } from "vue";
import { NUpload, NTabs, NTabPane, NH1, NH3, NSwitch, useMessage, UploadFileInfo } from "naive-ui";
import { checkSameQuestion, getTags, toCreateQuestion, toDeleteQuesiton } from "@/utils/Questions";
import { uploadHeaders } from "@/utils/global";

export default defineComponent({
    components: { NUpload, NTabs, NTabPane, NH1, NSwitch, NH3 },
    created() {
        this.setTags();
    },
    setup() {
        const message = useMessage();
        const uploadRef = ref();
        const dataRef = ref();
        return {
            message,
            uploadHeaders,
            description: uploadRef,
            data: dataRef,
            tags: ref(),
            difficulties: [
                {
                    label: '简单',
                    value: '简单'
                },
                {
                    label: '一般',
                    value: '一般'
                },
                {
                    label: '困难',
                    value: '困难'
                }
            ],
            uploadQuestion: ref({
                questionName: '',
                questionNo: 0,
                tags: 1,
                difficulty: '简单',
                editOnline: false,
                diff: false,
                description: '',
                files: {
                    description: {
                        exist: false
                    },
                    data: {
                        length: 0
                    },
                },
                uploadDescription: true,
                uploadData: true
            }),
            deleteQuestion: ref({
                questionName: '',
                canDelete: false
            })
        }
    },
    methods: {
        descriptionChange({ fileList }) {
            if (fileList.length == 1 || this.uploadQuestion.description.length > 0) {
                this.uploadQuestion.files.description.exist = true;
            }
        },
        dataChange({ fileList }) {
            this.uploadQuestion.files.data.length = fileList.length;
            if (this.uploadQuestion.files.data.length > 0 && this.uploadQuestion.files.data.length % 2 == 0) {
                this.uploadQuestion.uploadData = false;
            } else {
                this.uploadQuestion.uploadData = true;
            }
        },
        handleBeforeLeave(tabName: any): boolean {
            this.uploadQuestion.questionName = '';
            return true;
        },
        async setNo({ file, event }) {
            console.log('进入回调函数');
            const res = JSON.parse(event.target.response);
            this.uploadQuestion = res.question;
            this.data.data.question_id = res.question;
            console.log(this.data.data.question);
            try {
                this.data.submit();
                this.message.success('问题' + this.uploadQuestion.questionNo + '已上传成功');
                this.$router.replace('/');
            } catch (error) {
                console.log(error);
            }
            
        },
        async beforeUpload(options: { file: UploadFileInfo, fileList: UploadFileInfo[] }){
            console.log(options.file.file);
            if (options.file.file && options.file.file.name.split('.').pop() != 'md'){
                this.message.error('只能上传markdown文件(以.md结尾的文件)');
                return false;
            } else {
                return true;
            }
        },
        async beforeUploadData(options: { file: UploadFileInfo, fileList: UploadFileInfo[] }){
            console.log(options.file.file);
            if (!options.file.file) return ;
            const suffix = options.file.file.name.split('.').pop()
            if (suffix != 'in' && suffix != 'out'){
                this.message.error('只能上传 .in 和 .out 文件');
                return false;
            } else {
                return true;
            }
        },
        async handleClick() {
            if (this.description){
                this.description.submit();
            } else {
                if(!this.uploadQuestion.tags){
                    this.message.warning('还没选择标签')
                    return;
                }
                const question_id = await toCreateQuestion(this.uploadQuestion.questionName, this.uploadQuestion.description, this.uploadQuestion.tags, this.uploadQuestion.difficulty);
                if (question_id < 0) {
                    this.message.error('服务器出了点问题，待会再试试');
                } else if (question_id == 0) {
                    this.message.error('没有权限发布问题呢');
                } else {
                    this.data.data.question_id = question_id;
                    try {
                        await this.data.submit();
                        this.message.success('问题' + question_id + '已上传成功');
                        this.$router.replace('/');
                    } catch (error) {
                        console.log(error);
                        return -1;
                    }
                }
                console.log('没有文件')
            }
        },
        async check() {
            const flag = await checkSameQuestion(this.uploadQuestion.questionName);
            if (flag == 0) {
                this.uploadQuestion.diff = true;
                this.message.success('这个问题名字没有重复')
            } else if (flag == 1) {
                this.message.error('这个问题名字重复了，换一个')
            } else {
                this.message.error('服务器出了点问题，待会再试试')
            }
        },
        async setTags() {
            this.tags = await getTags();
        },
        async checkNoExists(){
            const _name = this.deleteQuestion.questionName;
            const flag = await checkSameQuestion(_name);
            if (flag == 0) {
                this.uploadQuestion.diff = true;
                this.message.error('没有找到这个问题')
            } else if (flag == 1) {
                this.message.success('找到了')
            } else {
                this.message.error('服务器出了点问题，待会再试试')
            }
        },
        async deleteQuestions(){
            const _name = this.deleteQuestion.questionName;
            const flag = await toDeleteQuesiton(_name);
            if (flag > 0) {
                this.message.success('删除问题' + flag + '成功');
                this.$router.replace('/');
            } else if (flag == 0) {
                this.message.error('确实没有这个问题可以删');
            } else {
                this.message.error('服务器出了点问题，待会再试试');
            }
        }
    }
});
</script>